import React, { useState, useCallback } from 'react'
import { X, Calendar, Hash, Search, Filter, RotateCcw } from 'lucide-react'

export interface MessageFilters {
  partition?: number
  timeRange?: {
    start: string // ISO string
    end: string   // ISO string
  }
  keyPattern?: string
  valuePattern?: string
  minOffset?: number
  maxOffset?: number
  useRegex?: boolean
  caseSensitive?: boolean
}

interface MessageFiltersProps {
  filters: MessageFilters
  onFiltersChange: (filters: MessageFilters) => void
  onApply: () => void
  onReset: () => void
  availablePartitions?: number[]
  loading?: boolean
  show: boolean
  onClose: () => void
}

export default function MessageFilters({
  filters,
  onFiltersChange,
  onApply,
  onReset,
  availablePartitions = [],
  loading = false,
  show,
  onClose
}: MessageFiltersProps) {
  const [localFilters, setLocalFilters] = useState<MessageFilters>(filters)

  const updateFilter = useCallback((key: keyof MessageFilters, value: any) => {
    const newFilters = { ...localFilters, [key]: value }
    setLocalFilters(newFilters)
    onFiltersChange(newFilters)
  }, [localFilters, onFiltersChange])

  const handleTimeRangeChange = useCallback((field: 'start' | 'end', value: string) => {
    const newTimeRange = {
      ...localFilters.timeRange,
      [field]: value
    }
    updateFilter('timeRange', newTimeRange)
  }, [localFilters.timeRange, updateFilter])

  const handleApply = useCallback(() => {
    onApply()
  }, [onApply])

  const handleReset = useCallback(() => {
    const emptyFilters: MessageFilters = {}
    setLocalFilters(emptyFilters)
    onFiltersChange(emptyFilters)
    onReset()
  }, [onFiltersChange, onReset])

  const hasActiveFilters = Object.keys(localFilters).some(key => {
    const value = localFilters[key as keyof MessageFilters]
    if (key === 'timeRange') {
      return value && (value.start || value.end)
    }
    return value !== undefined && value !== null && value !== ''
  })

  if (!show) return null

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div className="bg-white rounded-lg shadow-xl max-w-2xl w-full mx-4 max-h-[90vh] overflow-y-auto">
        {/* 头部 */}
        <div className="flex items-center justify-between p-6 border-b border-gray-200">
          <div className="flex items-center space-x-2">
            <Filter className="h-5 w-5 text-primary-600" />
            <h3 className="text-lg font-medium text-gray-900">消息过滤器</h3>
            {hasActiveFilters && (
              <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-primary-100 text-primary-800">
                已应用过滤条件
              </span>
            )}
          </div>
          <button
            onClick={onClose}
            className="p-2 hover:bg-gray-100 rounded-full"
          >
            <X className="h-5 w-5" />
          </button>
        </div>

        {/* 过滤条件 */}
        <div className="p-6 space-y-6">
          {/* 分区过滤 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              <Hash className="inline h-4 w-4 mr-1" />
              分区
            </label>
            <select
              value={localFilters.partition || ''}
              onChange={(e) => updateFilter('partition', e.target.value ? Number(e.target.value) : undefined)}
              className="w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-2 focus:ring-primary-500 focus:border-transparent"
            >
              <option value="">所有分区</option>
              {availablePartitions.map(partition => (
                <option key={partition} value={partition}>
                  分区 {partition}
                </option>
              ))}
            </select>
          </div>

          {/* 时间范围 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              <Calendar className="inline h-4 w-4 mr-1" />
              时间范围
            </label>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-xs text-gray-500 mb-1">开始时间</label>
                <input
                  type="datetime-local"
                  value={localFilters.timeRange?.start || ''}
                  onChange={(e) => handleTimeRangeChange('start', e.target.value)}
                  className="w-full border border-gray-300 rounded-md px-3 py-2 text-sm focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                />
              </div>
              <div>
                <label className="block text-xs text-gray-500 mb-1">结束时间</label>
                <input
                  type="datetime-local"
                  value={localFilters.timeRange?.end || ''}
                  onChange={(e) => handleTimeRangeChange('end', e.target.value)}
                  className="w-full border border-gray-300 rounded-md px-3 py-2 text-sm focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                />
              </div>
            </div>
          </div>

          {/* 偏移量范围 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              偏移量范围
            </label>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-xs text-gray-500 mb-1">最小偏移量</label>
                <input
                  type="number"
                  placeholder="例如: 0"
                  value={localFilters.minOffset || ''}
                  onChange={(e) => updateFilter('minOffset', e.target.value ? Number(e.target.value) : undefined)}
                  className="w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                />
              </div>
              <div>
                <label className="block text-xs text-gray-500 mb-1">最大偏移量</label>
                <input
                  type="number"
                  placeholder="例如: 1000"
                  value={localFilters.maxOffset || ''}
                  onChange={(e) => updateFilter('maxOffset', e.target.value ? Number(e.target.value) : undefined)}
                  className="w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                />
              </div>
            </div>
          </div>

          {/* Key模式匹配 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              <Search className="inline h-4 w-4 mr-1" />
              Key模式匹配
            </label>
            <input
              type="text"
              placeholder="输入Key的匹配模式..."
              value={localFilters.keyPattern || ''}
              onChange={(e) => updateFilter('keyPattern', e.target.value || undefined)}
              className="w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-2 focus:ring-primary-500 focus:border-transparent"
            />
            <p className="text-xs text-gray-500 mt-1">
              支持通配符匹配，例如: user_* 或 order_123
            </p>
          </div>

          {/* Value内容搜索 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              <Search className="inline h-4 w-4 mr-1" />
              Value内容搜索
            </label>
            <input
              type="text"
              placeholder="输入要搜索的Value内容..."
              value={localFilters.valuePattern || ''}
              onChange={(e) => updateFilter('valuePattern', e.target.value || undefined)}
              className="w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-2 focus:ring-primary-500 focus:border-transparent"
            />
            <p className="text-xs text-gray-500 mt-1">
              搜索消息Value中包含的文本内容
            </p>
          </div>

          {/* 搜索选项 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-3">搜索选项</label>
            <div className="space-y-2">
              <label className="flex items-center">
                <input
                  type="checkbox"
                  checked={localFilters.useRegex || false}
                  onChange={(e) => updateFilter('useRegex', e.target.checked)}
                  className="rounded border-gray-300 text-primary-600 focus:ring-primary-500"
                />
                <span className="ml-2 text-sm text-gray-700">使用正则表达式</span>
              </label>
              <label className="flex items-center">
                <input
                  type="checkbox"
                  checked={localFilters.caseSensitive || false}
                  onChange={(e) => updateFilter('caseSensitive', e.target.checked)}
                  className="rounded border-gray-300 text-primary-600 focus:ring-primary-500"
                />
                <span className="ml-2 text-sm text-gray-700">区分大小写</span>
              </label>
            </div>
          </div>

          {/* 预设快速过滤 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-3">快速过滤</label>
            <div className="grid grid-cols-2 gap-2">
              <button
                onClick={() => {
                  const now = new Date()
                  const oneHourAgo = new Date(now.getTime() - 60 * 60 * 1000)
                  updateFilter('timeRange', {
                    start: oneHourAgo.toISOString().slice(0, 16),
                    end: now.toISOString().slice(0, 16)
                  })
                }}
                className="px-3 py-2 text-sm border border-gray-300 rounded-md hover:bg-gray-50"
              >
                最近1小时
              </button>
              <button
                onClick={() => {
                  const now = new Date()
                  const oneDayAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000)
                  updateFilter('timeRange', {
                    start: oneDayAgo.toISOString().slice(0, 16),
                    end: now.toISOString().slice(0, 16)
                  })
                }}
                className="px-3 py-2 text-sm border border-gray-300 rounded-md hover:bg-gray-50"
              >
                最近24小时
              </button>
              <button
                onClick={() => updateFilter('keyPattern', 'user_*')}
                className="px-3 py-2 text-sm border border-gray-300 rounded-md hover:bg-gray-50"
              >
                用户相关
              </button>
              <button
                onClick={() => updateFilter('keyPattern', 'order_*')}
                className="px-3 py-2 text-sm border border-gray-300 rounded-md hover:bg-gray-50"
              >
                订单相关
              </button>
            </div>
          </div>
        </div>

        {/* 底部操作 */}
        <div className="flex items-center justify-between p-6 border-t border-gray-200 bg-gray-50">
          <button
            onClick={handleReset}
            disabled={loading || !hasActiveFilters}
            className="flex items-center space-x-2 px-4 py-2 text-gray-600 hover:text-gray-800 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <RotateCcw className="h-4 w-4" />
            <span>重置</span>
          </button>

          <div className="flex items-center space-x-3">
            <button
              onClick={onClose}
              className="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50"
            >
              取消
            </button>
            <button
              onClick={handleApply}
              disabled={loading}
              className="px-4 py-2 bg-primary-600 text-white rounded-md hover:bg-primary-700 disabled:opacity-50 disabled:cursor-not-allowed flex items-center space-x-2"
            >
              {loading && <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>}
              <span>应用过滤</span>
            </button>
          </div>
        </div>
      </div>
    </div>
  )
}
